<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工位" prop="stationCode" label-width="60px">
        <!-- <el-cascader
          v-model="queryParams.stationName"
          :options="treeGWOptions"
          :props="{value: 'shopCode', label: 'shopName'}"
          placeholder="请选择工位"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        ></el-cascader> -->
        <el-select
          v-model="queryParams.stationCode"
          placeholder="请选择工位"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in treeGWOptions"
            :key="item.shopCode"
            :label="item.shopName"
            :value="item.shopCode"
          >
            <span style="float: left">{{ item.shopCode }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.shopName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pull:lineStock:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pull:lineStock:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pull:lineStock:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pull:lineStock:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="stockList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="60" align="center" fixed="left" />
      <el-table-column label="库存组件id" align="center" width="100" fixed="left" prop="stockId" v-if="false" />
      <el-table-column label="物料编码" align="center" prop="materialCode" width="100" fixed="left" />
      <el-table-column label="物料名称" align="center" prop="materialName" width="200" />
      <el-table-column label="产线" align="center" prop="lineName" width="100" />
      <el-table-column label="工位" align="center" prop="stationCode" :formatter="getGWName" width="100" />
      <el-table-column label="库存数量" align="center" prop="stockNumber" width="100" />
      <el-table-column label="有效期" align="center" prop="validityPeriod" width="100" />
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="更新人" align="center" prop="updateBy" width="100" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="margin-right: 9px"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pull:lineStock:edit']"
          >数量调整</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pull:lineStock:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="物料名称" prop="dataId">
              <el-select
                v-model="form.dataId"
                placeholder="请选择物料名称"
                style="width: 240px"
                filterable
              >
                <el-option
                  v-for="item in materialOptions"
                  :key="item.dataId"
                  :label="item.invName"
                  :value="item.dataId"
                >
                  <span style="float: left">{{ item.invCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.invName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="工位" prop="stationCode">
              <!-- <el-cascader
                v-model="form.stationCode"
                :options="treeGWOptions"
                :props="{value: 'shopCode', label: 'shopName'}"
                placeholder="请选择工位"
                style="width: 240px"
              ></el-cascader> -->
              <el-select
                v-model="form.stationCode"
                placeholder="请选择工位"
                style="width: 240px"
                :disabled="editType"
              >
                <el-option
                  v-for="item in treeGWOptions"
                  :key="item.shopCode"
                  :label="item.shopName"
                  :value="item.shopCode"
                >
                  <span style="float: left">{{ item.shopCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.shopName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="库存数据" prop="stockNumber">
              <el-input
                v-model="form.stockNumber"
                placeholder="请输入库存数据"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="有效期(日)" prop="validityPeriod">
              <el-input
                v-model="form.validityPeriod"
                placeholder="请输入有效期"
                style="width: 240px"
                :disabled="editType"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listStock,
    getStock,
    delStock,
    addStock,
    updateStock,
    getTree,
    exportStock,
  } from "@/api/pull/lineStock";
  import { listAllMaterial } from "@/api/base/materialERP";

  export default {
    name: "LineStock",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 修改状态
        editType: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 库存表格数据
        stockList: [],
        // 物料下拉
        materialOptions: [],
        // 工位下拉
        treeGWOptions: [],
        // 弹出层标题
        title: "",
        separateTitle: "",
        // 是否显示弹出层
        open: false,
        separateOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          materialCode: undefined,
          materialName: undefined,
          stationCode: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          dataId: [{ required: true, message: "物料编码不能为空", trigger: "change" }],
          stationCode: [{ required: true, message: "工位不能为空", trigger: "change" }]
        }
      };
    },
    created() {
      this.getTreeGW();
      this.getMaterialList();
      this.getList();
    },
    methods: {
      /** 查询生产计划列表 */
      getList() {
        this.loading = true;
        listStock(this.queryParams).then(response => {
          this.stockList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 查询工位树
      getTreeGW() {
        getTree(4).then(response => {
          // const newData = this.getTreeData(response.data);
          this.treeGWOptions = response.data;
        });
      },
      // 查询物料列表
      getMaterialList() {
        listAllMaterial({}).then(response => {
          this.materialOptions = response.data;
        });
      },
      // 递归树形
      // getTreeData(treeData) {
      //   for (let i = 0; i < treeData.length; i++) {
      //     if (treeData[i].children.length === 0) {
      //       treeData[i].children = undefined;
      //     } else {
      //       this.getTreeData(treeData[i].children);
      //     }
      //   }
      //   return treeData;
      // },
      // 查询工位名称
      getGWName(row, column) {
        let name = '';
        const data = this.treeGWOptions.filter((item, index) => item.shopCode === row.stationCode);
        name = data[0]?.shopName;
        return name;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      separateCancel() {
        this.separateOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.stockId);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.editType = false;
        this.reset();
        this.open = true;
        this.title = "添加库存";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.editType = true;
        this.reset();
        const stockIds = row.stockId || this.ids;
        getStock(stockIds).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改库存";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.stockId != null) {
              updateStock(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addStock(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const stockIds = row.stockId || this.ids;
        this.$confirm('是否确认删除库存编号为"' + stockIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStock(stockIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有库存数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStock(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
